'''
都健康  全民百万医疗
'''

import sys

sys.path.append('../')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests, json, time
from common.helper import Helper
from urllib.parse import urlencode


class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "都健康  全民百万医疗"

    # 生成产品数据
    def genProductInfo(self):
        plan = {

            # 年龄段 1 - 60
            "year": [str(i) for i in range(1, 61)],
            # 有无社保 true 有社保 false 无社保
            "socialSec": ["true", "false"]

        }
        for v in product(plan["year"], plan["socialSec"]):
            # 保险金额
            money = "200w"
            # 附加质子重离子治疗保险金
            ext_item = "200w"

            self.mysql.cursor.execute(
            domain[self.name]["insert_sql"].format(v[0], v[1],money,ext_item));self.mysql._conn.commit();print("%s产品信息保存成功"%self.name )

    #执行爬虫
    def requestJson(self,dt=None,true=None):

        data = {

            "req":{"ts":"","t1":0,"account":"","payload":{"cmd":"CalculatePremium","birthday":"{year}-12-24".format( year = str(2019-int(dt["year"]))),"socialInsued":dt["socialSec"]},"digest":"","udid":"","mudid":"","bundle_id":"","ostype":"unknown","osmodel":"","osversion":"","appversion":""},
            "connect_redirect":1

        }

        data = urlencode( data ).replace('+','')

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=data)

        if r.status_code == 200 and r.json()["payload"]["result"]:

            price = Helper.decimalParse( r.json()["payload"]["vo"]["premium"] )

            data = {

                "name":self.name,
                "id":dt["id"],
                "price":price
            }

            self.mysql.updatePrice( data )

        else:

            data = {

                "name":self.name,
                "id":dt["id"],
                "state":3
            }

            self.mysql.updateTask( data )

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:
                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson(dt)
